package com.heima.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.heima.constant.RedisConstant;
import com.heima.exception.BaseException;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.service.UserService;
import com.heima.utils.AliyunOssUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author ljk74
 */
@RestController
@Slf4j
@Api(tags = "公共接口")
@RequiredArgsConstructor
public class CommonController {
    private final UserService userService;
    private final RedisTemplate redisTemplate;
    private final AliyunOssUtil aliyunOssUtil;

    private String newFileName(String suffix){
        String folderName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        String fileName = UUID.randomUUID().toString() + suffix;
        return folderName+"/"+fileName;
    }

    @ApiOperation("登录")
    @PostMapping("/api/user-service/user/login")
    public LoginUserVo login(@RequestBody LoginDto dto){
        log.debug("登录传入的数据:{}",dto);
        return userService.login(dto);
    }

    @PostMapping("/api/vm-service/sku/fileUpload")
    @ApiOperation("图片上传")
    public String uploadImage(MultipartFile fileName){
        log.debug("文件上传:{}",fileName);
        try{
            //获得原始文件名
            String originalFilename = fileName.getOriginalFilename();
            //截取后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接新的文件名
            String newFileName = newFileName(suffix);
            return aliyunOssUtil.upload(fileName.getBytes(),newFileName);
        }catch (IOException e){
            log.error("文件上传失败",e);
        }
        return "文件上传失败";
    }

    @ApiOperation("图片验证码")
    @GetMapping("/api/user-service/user/imageCode/{clientToken}")
    public void imageCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String clientToken) throws IOException {
        //设置输出头为输出图片类型
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, Accept");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setDateHeader("Expires", 0);
        //生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130,50,4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        String code = specCaptcha.text().toLowerCase();
        String key = clientToken;
        //存入redis
        redisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.MINUTES);
        //输出 图片输出流
        specCaptcha.out(response.getOutputStream());

    }
}
